use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, SocketAddr};
use std::thread;

fn handle_client(mut stream: TcpStream, client_addr: SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
    println!("新客户端连接: {}", client_addr);
    
    let mut buffer = [0; 512];
    
    loop {
        // 读取客户端数据
        let bytes_read = stream.read(&mut buffer)?;
        if bytes_read == 0 {
            println!("客户端 {} 断开连接", client_addr);
            break; // 连接已关闭
        }
        
        let received = String::from_utf8_lossy(&buffer[..bytes_read]);
        println!("来自 {} 的数据: {}", client_addr, received);
        
        if received.trim() == "/quit" {
            println!("客户端 {} 请求断开连接", client_addr);
            break;
        }
        
        // 将原数据发送回客户端
        if let Err(e) = stream.write_all(&buffer[..bytes_read]) {
            eprintln!("向客户端 {} 发送数据失败: {}", client_addr, e);
            break;
        }
        
        println!("向客户端 {} 发送原数据: {}", client_addr, received);
        
        // 清空缓冲区以备下次使用
        buffer = [0; 512];
    }
    
    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("双向通信服务器启动");
    println!("监听地址: 127.0.0.1:5050");
    println!("---------------");
    
    // 绑定到本地地址的5050端口
    let listener = TcpListener::bind("127.0.0.1:5050")?;
    
    // 接受连接并处理它们
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                // 获取客户端地址
                let client_addr = stream.peer_addr()?;
                println!("接收到来自 {} 的连接", client_addr);
                
                // 为每个连接创建新线程
                thread::spawn(move || {
                    if let Err(e) = handle_client(stream, client_addr) {
                        eprintln!("处理客户端 {} 时出错: {}", client_addr, e);
                    }
                });
            }
            Err(e) => {
                eprintln!("连接失败: {}", e);
            }
        }
    }
    
    Ok(())
}